<?php

namespace mybackend\controllers\mtp;

use common\services\common\MyscrmAuthorizeService;
use common\services\common\MyscrmContractService;
use common\services\common\MyscrmPackageService;
use common\services\common\MyscrmOrganizationService;
use common\services\outstock\FlowCenterService;
use mybackend\controllers\BaseController;
use common\entities\myhtsq\ActionCode;

use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\Response;
use Yii;

/**
 * Site controller
 */
class MyscrmOrganizationController extends BaseController
{

    private $_myscrmOrganizationService = null;
    private $_packageService = null;
    private $_contractService = null;
    private $_authorizeService = null;
    private $_request = null;
    public $enableCsrfValidation = false;
    public $layout = '@app/views/mtp/layouts/main.php';
    private $_show = false;

    public function __construct($id, $module,
                                MyscrmOrganizationService $myscrmOrganizationService,
                                MyscrmPackageService $packageService,
                                MyscrmContractService $contractService,
                                MyscrmAuthorizeService $authorizeService,
                                $config = [])
    {
        $this->_myscrmOrganizationService = $myscrmOrganizationService;
        $this->_packageService = $packageService;
        $this->_contractService = $contractService;
        $this->_authorizeService = $authorizeService;
        $this->_request = Yii::$app->request;

        //设置阿里云rds组件
        Yii::$app->setComponents(['rds' => [
            'class' => 'common\components\aliyun\Rds',
        ]]);

        parent::__construct($id, $module, $config);
    }

    protected function roleAuthRules()
    {
        return [
            'actions' => ['CreateOrganization','UpdateAll400Pwd','GetPackagesByOrg','GetProjectAuthContractList', 'GetNewestReason', 'ExportOrgProjectAuthList','UpdateRemind', 'UpdateDeliverInfo'],
            'rules' => [
                [
                    'allow' => true,
                    'actionCodeMaps' => [
                        'CreateOrganization' => ActionCode::EXP_LIST_MOD,
                        'UpdateAll400Pwd' => ActionCode::EXP_LIST_MOD,
                        'GetPackagesByOrg' => ActionCode::EXP_LIST_VIEW,
                        'GetProjectAuthContractList' => ActionCode::EXP_AUTH_VIEW,
                        'GetNewestReason' => ActionCode::EXP_AUTH_VIEW,
                        'ExportOrgProjectAuthList' => ActionCode::XMSQ_EXPORT,
                        'UpdateRemind' => ActionCode::EXP_BZTX_MOD,
                        'UpdateDeliverInfo' => ActionCode::EXP_JFXX_MOD,
                    ]
                ]
            ]
        ];
    }

    public function actionIndex()
    {
        return $this->render("index");
    }

    public function beforeAction($action)
    {
        if ($this->_request->request("show", false)) {
            $this->_show = true;
        }
        return parent::beforeAction($action);
    }

    /*
     *
     * Author yuyj
     * Date 2017-01-09
     * @apiVersion 1.0.0
     * @api {get} /api/index.php/mtp/myscrm-organization/get-orgs 获取租户列表
     * @apiGroup myscrm-organization-controller
     *
     * @apiParam query {string} keyword 关键字
     * @apiParam query {string} isBq 是否百强1:只显示百强,0:显示所有
     * @apiParam query {string} page 页码
     * @apiParam query {string} pageSize 每页数
     *
     * @apiResponse 200 {
     *  "retCode": 0,
     *  "errMsg": "",
     *  "data":{"total":"30",
     * "items":[{
     * "Id":"39d50450-d1e7-b7ad-ff6f-370d2c65fa41",
     * "DatabaseName":"myscrm_ydjtadmin_test",
     * "InstanceName":"rdsyn7zzryn7zzr",
     * "InstanceId":"rdsyn7zzryn7zzr",
     * "UniqueName":"ydjtadmin",
     * "FriendlyName":"悦达集团",
     * "State":"0",
     * "Email":"fuxl@mysoft.com.cn",
     * "UpgradeSerialNumber":"265",
     * "IsCanUpgrade":"1",
     * "CreatedOn":"2015-12-30 17:07:02",
     * "ModifiedOn":"2015-12-30 17:07:02",
     * "CustomManager":"武汉微信开发ABU",
     * "CustomManagerPhone":"",
     * "CustomManagerEmail":"",
     * "Deliver":"陈行辉",
     * "DeliverPhone":"15977726636",
     * "DeliverEmail":"chenxh01@mysoft.com.cn",
     * "ScheduleKey":"121.40.177.30",
     * "Area":"南京",
     * "LogoUrl":"",
     * "CustomManagerGUID":"f591cb51-a6a5-e311-ab0d-848f69dfab18",
     * "DeliverGUID":"b8b6bf92-cbdb-4de3-98e1-121e44828626",
     * "isBq":"1"
     * }
     * ]}
     * }
     */
    public function actionGetOrgs()
    {
        $requestData = $this->_request->request();
        $_order = ArrayHelper::getValue($requestData, 'order', "desc");
        $keyword = ArrayHelper::getValue($requestData, 'keyword', '');
        $isBq = ArrayHelper::getValue($requestData, 'isBq', '');
        $page = intval(ArrayHelper::getValue($requestData, 'page', 1));
        $pageSize = intval(ArrayHelper::getValue($requestData, 'pageSize', 10));

        $isTest = ArrayHelper::getValue($requestData, 'isTest', '');


        if ($_order == 'desc') {
            $_order = SORT_DESC;
        } else {
            $_order = SORT_ASC;
        }

        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try {
            $orgs = $this->_myscrmOrganizationService->getOrganizationListByPage(
                $keyword,
                $isBq,
                $isTest,
                $page,
                $pageSize);
        } catch (\Exception $ex) {
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }
        if ($this->_show) {
            return $this->render('orgs-list', ['orgs' => $orgs]);
        } else {
            if (!empty($orgs)) {
                $response['data'] = $orgs;
            }
            return $this->json($response);
        }
    }

    public function actionAddPackage()
    {
        $this->_packageService->addPackage($this->_request->post());
    }

    public function actionGetPackages()
    {
        return $this->json($this->_packageService->getAllPackage('unique_name', SORT_DESC));
    }


    public function actionAddAppToPkg()
    {
        return $this->json($this->_packageService->addApplicationToPackage($this->_request->post('package_id'), $this->_request->post('application_id')));
    }

    public function actionDelNoUseAppInPkg()
    {
        return $this->json($this->_packageService->delNoUsePackageApplication());
    }

    public function actionModifyPkgPrice()
    {
        return $this->json($this->_packageService->modifyPackagePrice($this->_request->post('package_id'),
            $this->_request->post('price'), $this->_request->post('unit')));
    }

    public function actionAppInPkg()
    {
        return $this->json($this->_packageService->getApplicationInPackage($this->_request->post('package_id')));
    }

    public function actionGetOrgById()
    {
        return $this->json($this->_myscrmOrganizationService->getOrgById($this->_request->post('id')));
    }

    /**
     * 新增或更改合同
     * @return mixed
     */
    public function actionSaveContract()
    {

        $post = $this->_request->post();
        if (!array_key_exists('contract_num', $post) || !array_key_exists('party_a', $post) ||
            !array_key_exists('contract_type', $post) || !array_key_exists('begin_on', $post) ||
            !array_key_exists('end_on', $post) || !array_key_exists('organization_id', $post) ||
            !array_key_exists('auth_info', $post) || !array_key_exists('area_id', $post)
        ) {
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "参数不能为空"]);
        }

        $orderCode = ArrayHelper::getValue($post, 'order_code');
        $contractId = ArrayHelper::getValue($post, 'contract_id');
        $contractNum = ArrayHelper::getValue($post, 'contract_num');
        $partyA = ArrayHelper::getValue($post, 'party_a');
        $contractType = ArrayHelper::getValue($post, 'contract_type');
        $beginOn = ArrayHelper::getValue($post, 'begin_on');
        $endOn = ArrayHelper::getValue($post, 'end_on');
        $organizationId = ArrayHelper::getValue($post, 'organization_id');
        $authInfo = ArrayHelper::getValue($post, 'auth_info');
        $areaId = ArrayHelper::getValue($post, 'area_id');
        $establishTime = ArrayHelper::getValue($post, 'establish_time');
        $authType = ArrayHelper::getValue($post, 'authType');
        $category = ArrayHelper::getValue($post, 'category');
        $promiseFulfilTime = ArrayHelper::getValue($post, 'promiseFulfilTime');
        $actualFulfilTime = ArrayHelper::getValue($post, 'actualFulfilTime');
        $promiseFulfilPrinciple = ArrayHelper::getValue($post, 'promiseFulfilPrinciple');
        $authType=intval($authType);
        if($authType==4){
            if(empty($category)){
                $this->exportJson([],"-1","特批类型不能为空");
            }
            if(empty($promiseFulfilTime)){
                $this->exportJson([],"-1","承诺兑现日期不能为空");
            }
            if(empty($promiseFulfilPrinciple)){
                $this->exportJson([],"-1","兑现责任人不能为空");
            }
        }

        $contractModel = [
            'contract_id' => $contractId,
            'contract_num' => $contractNum,
            'party_a' => $partyA,
            'organization_id' => $organizationId,
            'contract_type' => $contractType,
            'begin_on' => $beginOn,
            'end_on' => $endOn,
            'auth_info' => json_decode($authInfo, True),
            'area_id' => $areaId,
            'establish_time' => $establishTime,
            'authType' => $authType,
            'category' => $category,
            'promiseFulfilTime' => $promiseFulfilTime,
            'actualFulfilTime' => $actualFulfilTime,
            'promiseFulfilPrinciple' => $promiseFulfilPrinciple,
            'order_code' => $orderCode
        ];

        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try {
            $result = $this->_contractService->saveContract($contractModel);
        } catch (\Exception $ex) {
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }

        if (!empty($result)) {
            $response['data'] = 1;
        } else {
            $response['retCode'] = -1;
            $response['retMsg'] = '保存失败';
            $response['result'] = false;
        }
        return $this->json($response);

    }

    public function actionGetContracts()
    {
        return $this->json($this->_contractService->getContractsByOrgId(ArrayHelper::getValue($this->_request->post(), "organization_id")));
    }

    /**
     * 获取合同列表
     * @return mixed
     */
    public function actionGetContractsList()
    {
        $requestData = $this->_request->request();
        if (!array_key_exists('orgname', $requestData)) {
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "租户企业号不能为空"]);
        }
        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try {
            $list = $this->_contractService->getContractsList(ArrayHelper::getValue($requestData, "orgname"));
        } catch (\Exception $ex) {
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }

        if (!empty($list)) {
            $response['data'] = $list;
        } else {
            $response['retCode'] = -1;
            $response['retMsg'] = '获取失败';
            $response['result'] = false;
        }
        if (array_key_exists('show', $requestData)) {
            return $this->render('contracts-list', ['list' => $list, 'orgName' => ArrayHelper::getValue($requestData, 'orgname')]);
        } else {
            return $this->json($response);
        }


    }

    /**
     * 作废合同
     */
    public function actionCancelContract()
    {
        $postData = $this->_request->post();
        if (!array_key_exists('orgname', $postData) || !array_key_exists('contract_id', $postData)) {
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "缺少参数"]);
        }

        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];

        try {

            $this->_contractService->cancelContract(ArrayHelper::getValue($postData, 'orgname'), ArrayHelper::getValue($postData, 'contract_id'));
        } catch (\Exception $ex) {
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }

        return $this->json($response);

    }

    public function actionGetContract()
    {
        return $this->json($this->_contractService->getContractById(ArrayHelper::getValue($this->_request->post(), "contract_id")));
    }

    public function actionGetAuthorizedAppByCode()
    {
        return $this->json($this->_authorizeService->getAuthorizedAppByCode(
            ArrayHelper::getValue($this->_request->post(), "orgname"),
            ArrayHelper::getValue($this->_request->post(), "authcode")
        )
        );
    }

    public function actionGetAuthorizedAppsByOrgName()
    {
        if (ArrayHelper::getValue($this->_request->request(), "show", 0)) {
            return $this->render("apps-list", ["apps" => $this->_authorizeService->getAuthorizedAppsByOrgName(
                ArrayHelper::getValue($this->_request->request(), "orgname")
            )]);
        } else {
            return $this->json($this->_authorizeService->getAuthorizedAppsByOrgName(
                ArrayHelper::getValue($this->_request->request(), "orgname")
            ));
        }

    }

    public function actionGetAuthorizedPackagesByOrgName()
    {
        $reqData = array_merge($this->_request->post(), $this->_request->get());

        return $this->json($this->_authorizeService->getAuthorizedPackagesByOrgName(
            ArrayHelper::getValue($reqData, "orgname")
        ));
    }

    public function actionGetAuthorizedPackagesByOrgNameNoCurl()
    {
        $reqData = array_merge($this->_request->post(), $this->_request->get());
        return $this->json($this->_authorizeService->getAuthorizedPackagesByOrgNameNoCurl(
            ArrayHelper::getValue($reqData, "orgname")
        ));
    }

    /**
     * 新租户降级
     * @return mixed
     */
    public function actionOrgDegradation()
    {
        return $this->json(["retCode" => -1, "result" => false, "retMsg" => "功能已取消"]);
    }

    /**
     * 老租户升级
     * @return mixed
     */
    public function actionOrgUpgrade()
    {
        return '<div style="color:red">功能已取消</div>';

    }

    public function actionGetPackagesByOrg()
    {
        $requestData = $this->_request->request();

        if (!array_key_exists('orgname', $requestData)) {
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "租户企业号不能为空"]);
        }

        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try {
            $pkgs = $this->_authorizeService->getAuthorizedInfoByOrgName(
                ArrayHelper::getValue($requestData, 'orgname')
            );
        } catch (\Exception $ex) {
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }

        if (!empty($pkgs)) {
            $response['data'] = $pkgs;
        }

        if (array_key_exists('show', $requestData)) {
            return $this->render("authorized-packages", ["pkgs" => $pkgs]);
        } else {
            return $this->json($response);
        }

    }

    /**
     * 拿到已授权数
     * @return mixed
     */
    public function actionGetUsedAuthorizeNum()
    {
        return $this->json($this->_authorizeService->getUsedAuthorizeNum($this->_request->request('orgname')));
    }

    /**
     * 添加合同
     */
    public function actionAddContractForm()
    {
        $orgId = $this->_myscrmOrganizationService->getOrgId(ArrayHelper::getValue($this->_request->request(), "orgname"));
        $pkgs = $this->_packageService->getAllPackage();
        return $this->render("add-contract-form", ["orgId" => $orgId, 'pkgs' => $pkgs]);
    }

    /**
     * 编辑合同
     */
    public function actionEditContractForm()
    {
        $orgId = $this->_myscrmOrganizationService->getOrgId(ArrayHelper::getValue($this->_request->request(), "orgname"));
        $contract = $this->_contractService->getContractDetailById(ArrayHelper::getValue($this->_request->request(), "orgname"),
            ArrayHelper::getValue($this->_request->request(), "contract_id"));
        return $this->render("edit-contract-form", ["orgId" => $orgId, 'contract' => $contract]);
    }

    /**
     * 获取合同信息
     */
    public function actionGetContractInfo()
    {
        $requestData = $this->_request->request();
        if (!array_key_exists('orgname', $requestData)) {
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "租户企业号不能为空"]);
        }
        if (!array_key_exists('contract_id', $requestData)) {
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "租户合同ID不能为空"]);
        }
        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try {
            $contract = $this->_contractService->getContractDetailById(ArrayHelper::getValue($this->_request->request(), "orgname"),
                ArrayHelper::getValue($this->_request->request(), "contract_id"));
        } catch (\Exception $ex) {
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }
        $response['data'] = $contract;
        return $this->json($response);
    }

    /**
     * 获取所有的包
     * @return mixed
     */
    public function actionGetAllPackages()
    {
        $orgCode = Yii::$app->request->post('orgCode', '');

        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try {
            $pkgs = $this->_authorizeService->getAllApplications();
            $pkgs_withOutWlsOld = $pkgs;

            $hasWlsOld = $this->_authorizeService->hasBindApplication($orgCode, '5009');
            if(!$hasWlsOld){
                $pkgs = [];
                //如果没有绑定过微楼书旧版，则移除旧版微楼书，只显示新版微楼书
                foreach ($pkgs_withOutWlsOld as $item){
                    if($item['unique_name'] != '5001'){
                        $pkgs[] = $item;
                    }
                }
            }
        } catch (\Exception $ex) {
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }
        $response['data'] = $pkgs;
        return $this->json($response);
    }

    public function actionIsBuyZsslc()
    {
        return $this->json($this->_authorizeService->isBuyZsslc(ArrayHelper::getValue($this->_request->request(), "orgname")));

    }

    /**
     * 更新租户交付信息
     * @return mixed
     */
    public function actionUpdateDeliverInfo()
    {

        $this->exitIfNotPost();

        $requestData = $this->_request->request();
        if (!array_key_exists('orgname', $requestData)) {
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "租户企业号不能为空"]);
        }

        if (!array_key_exists('deliver_guid', $requestData)) {
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "交付顾问的用户ID不能为空"]);
        }
        if (!array_key_exists('custom_manager_guid', $requestData)) {
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "客户经理的用户ID不能为空"]);
        }


        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try {
            $this->_myscrmOrganizationService->updateOrganizationDeliverInfo($requestData);
        } catch (\Exception $ex) {
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }

        return $this->json($response);
    }

    function actionGetContactTotalNum()
    {
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getContactTotalNum(ArrayHelper::getValue($reqData, 'orgname'),
            ArrayHelper::getValue($reqData, 'contract_id')));
    }

    function actionGetAuthorizeTotalNum()
    {
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getAuthorizeTotalNum(ArrayHelper::getValue($reqData, 'authorize_id')));
    }

    function actionGetAuthorizedPackageById()
    {
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getAuthorizedPackageById(ArrayHelper::getValue($reqData, 'orgname'),
            ArrayHelper::getValue($reqData, 'package_id')));
    }

    function actionGetAuthorizedPackagesAndContractsByOrgName()
    {
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getAuthorizedPackagesAndContractsByOrgName(ArrayHelper::getValue($reqData, 'orgname')));
    }

    function actionGetAuthorizePackageAppBrothersAuthorId()
    {
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getAuthorizePackageAppBrothersAuthorId(ArrayHelper::getValue($reqData, 'orgname'),
            ArrayHelper::getValue($reqData, 'auth_id')));
    }

    function actionGetOldOrgPackagesByOrgName()
    {
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getOldOrgPackagesByOrgName(ArrayHelper::getValue($reqData, 'orgname')));
    }

    function actionIsMvp810()
    {
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->IsMvp810(ArrayHelper::getValue($reqData, 'orgname')));
    }

    function actionGetPkgPrice()
    {
        $reqData = $this->_request->request();
        return $this->json($this->_packageService->getPackagePrice(ArrayHelper::getValue($reqData, 'pkg_id')));
    }

    function actionGetPkgPriceByName()
    {
        $reqData = $this->_request->request();
        return $this->json($this->_packageService->getPackagePriceByName(ArrayHelper::getValue($reqData, 'pkg_name')));
    }

    function actionGetProjectBindAppNum()
    {
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getProjectBindAppNum(ArrayHelper::getValue($reqData, 'orgname')));
    }

    function actionGetProjectIds()
    {
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getProjectIds(ArrayHelper::getValue($reqData, 'orgname')));
    }

    /**
     * 需要续签的项目列表
     * 取数规则调整：取所有的项目应用
     */
    public function actionGetNeedRenewedProjects()
    {
        $orgCode = Yii::$app->request->get('orgname', '');
        $keyword = Yii::$app->request->get('keyword', '');

        $data = $this->_authorizeService->getNeedRenewedProjects($orgCode, $keyword);
        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 项目禁用列表
     * @return \mybackend\controllers\type
     * @throws \Exception
     */
    public function actionGetProjectAuthContractList()
    {
        $reqData = $this->_request->request();
        $orgCode = ArrayHelper::getValue($reqData, 'orgCode');
        $pageIndex = ArrayHelper::getValue($reqData, 'pageIndex');
        $pageSize = ArrayHelper::getValue($reqData, 'pageSize');
        $status = ArrayHelper::getValue($reqData, 'status');
        $projectName = ArrayHelper::getValue($reqData, 'projName');

        $data = $this->_authorizeService->getProjectAuthContractList($orgCode, $projectName, $status, $pageIndex, $pageSize);
        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 改变禁用状态
     */
    public function actionChangeDisable()
    {
        try {
            //if not a right json format,it will throw BadRequestHttpException
            $disableItems = Yii::$app->request->post('items', '');
            if (!is_array($disableItems) || empty($disableItems)) {
                throw new \Exception("非法参数");
            }
            $data = $this->_authorizeService->changeDisable($disableItems);
            return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
        } catch (\Exception $e) {
            return $this->exportJson(false, __LINE__, $e->getMessage());
        }
    }

    /**
     * 获取最新一条原因
     */
    public function actionGetNewestReason()
    {
        $reqData = $this->_request->request();
        $orgCode = ArrayHelper::getValue($reqData, 'orgCode');
        $p_projectId = ArrayHelper::getValue($reqData, 'p_projectId');
        $applicationCode = ArrayHelper::getValue($reqData, 'application_code');

        $data = $this->_authorizeService->getNewestReason($orgCode, $p_projectId, $applicationCode);
        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 获取所有禁用原因记录
     */
    public function actionGetListByProjectIdApplicationCode()
    {
        $reqData = $this->_request->request();
        $orgCode = ArrayHelper::getValue($reqData, 'orgCode');
        $p_projectId = ArrayHelper::getValue($reqData, 'p_projectId');
        $applicationCode = ArrayHelper::getValue($reqData, 'application_code');

        $data = $this->_authorizeService->getListByProjectIdApplicationCode($orgCode, $p_projectId, $applicationCode);
        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 获取续签合同列表
     */
    public function actionGetOverdueOr30daysOverdueContracts()
    {
        $reqData = $this->_request->request();
        $data = $this->_authorizeService->getOverdueOr30daysOverdueContracts(ArrayHelper::getValue($reqData, 'orgname'));
        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 获取应用授权情况
     */
    public function actionGetApplicationAuthInfo()
    {
        $reqData = $this->_request->request();
        $orgName = ArrayHelper::getValue($reqData, 'orgname');
        $contractId = ArrayHelper::getValue($reqData, 'contract_id');
        $data = $this->_authorizeService->getApplicationAuthInfo($orgName, $contractId);
        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 获取续签中要显示的应用
     */
    public function actionGetApplicationList()
    {
        $data = $this->_authorizeService->getApplicationListByApplicationCodes();
        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 获取项目跟应用的关系（续签中哪些应用可以授权，哪些不能授权）
     */
    public function actionProjectApplicationRelation()
    {
        $orgName = $this->getRequest()->post('orgname');
        $projects = $this->getRequest()->post('projects');

        $data = $this->_authorizeService->getProjectApplicationRelation($orgName, $projects);

        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 获取指定合同的授权绑定情况
     */
    public function actionGetApplicationToProjectToAuthorizes()
    {
        $reqData = $this->_request->request();
        $orgName = ArrayHelper::getValue($reqData, 'orgname');
        $contractId = ArrayHelper::getValue($reqData, 'contract_id');

        $data = $this->_authorizeService->getApplicationToProjectToAuthorizes($orgName, $contractId);

        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 保存绑定授权
     * @author wangwx
     */
    public function actionSaveBindingAuth()
    {
        $this->exitIfNotPost();
        $orgName = $this->getRequest()->post('orgname');
        $auth = $this->getRequest()->post('auth');

        if (empty($auth)) {
            $this->exportJson(true, 0, '');
        }

        $data = $this->_authorizeService->SaveBindingAuth($orgName, $auth);

        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 获取RDS所有实例列表
     */
    public function actionGetRdsDatabaseInstanceList()
    {
        $data = $this->_myscrmOrganizationService->getRDSDatabaseInstanceList();
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 删除租户
     * @return string json
     */
    public function actionDeleteOrganization()
    {
        $reqData = $this->_request->request();
        $organizationId = ArrayHelper::getValue($reqData, 'organizationId');
        $reason = ArrayHelper::getValue($reqData, 'reason');

        if (!$reason || !$organizationId) {
            return $this->exportJson(false, __LINE__, '参数有误');
        }
        $data = $this->_myscrmOrganizationService->deleteOrganization($organizationId, $reason);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 更新租户状态（启用/禁用）
     * @return string json
     */
    public function actionUpdateOrganizationState()
    {
        $reqData = $this->_request->request();
        $organizationId = ArrayHelper::getValue($reqData, 'organizationId');
        $reason = ArrayHelper::getValue($reqData, 'reason');
        $state = ArrayHelper::getValue($reqData, 'state');

        if (empty($reason) || empty($organizationId)) {
            return $this->exportJson(false, __LINE__, '参数有误');
        }
        $data = $this->_myscrmOrganizationService->updateOrganizationState($organizationId, $state, $reason);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 重置管理员密码
     * @return string json
     */
    public function actionResetPwd()
    {
        $reqData = $this->_request->request();
        $organizationId = ArrayHelper::getValue($reqData, 'organizationId');
        $pwd = ArrayHelper::getValue($reqData, 'pwd');
        $email = ArrayHelper::getValue($reqData, 'email');

        if (!$pwd || !$organizationId || !$email) {
            return $this->exportJson(false, __LINE__, '参数有误');
        }
        $data = $this->_myscrmOrganizationService->resetPwd($organizationId, $pwd, $email);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 获取短信概况
     */
    public function actionGetSmsQuota()
    {
        $reqData = $this->_request->request();
        $organizationId = ArrayHelper::getValue($reqData, 'organizationId');

        if (!$organizationId) {
            return $this->exportJson(false, __LINE__, '参数有误');
        }
        $data = $this->_myscrmOrganizationService->getSmsQuota($organizationId);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 赠送短信
     * @return string json
     */
    public function actionAddSmsQuota()
    {
        $organizationId = $this->getRequest()->post('organizationId');
        $addQuota = $this->getRequest()->post('addQuota');
        $amount = $this->getRequest()->post('amount', 0);

        if(empty($amount)){
            $amount = 0;
        }

        if (!$organizationId || !$addQuota) {
            return $this->exportJson(false, __LINE__, '参数有误');
        }
        $data = $this->_myscrmOrganizationService->addSmsQuota($organizationId, $addQuota, $amount);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 修改所有400用户密码
     */
    public function actionUpdateAll400Pwd()
    {
        $reqData = $this->_request->request();
        $pwd = ArrayHelper::getValue($reqData, 'pwd');
        if (!$pwd) {
            return $this->exportJson(false, __LINE__, '参数有误');
        }
        $data = $this->_myscrmOrganizationService->updateAll400Pwd($pwd);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getLogMsg());
    }

    /**
     * 创建租户实例
     * @return string json
     */
    public function actionCreateOrganization()
    {
        $reqData = $this->_request->request();
        $uniqueName = ArrayHelper::getValue($reqData, 'uniqueName');
        $friendlyName = ArrayHelper::getValue($reqData, 'friendlyName');
        $instanceId = ArrayHelper::getValue($reqData, 'instanceId');
        $email = ArrayHelper::getValue($reqData, 'email');
        $orderCode = ArrayHelper::getValue($reqData, 'orderCode');
        $isTest = ArrayHelper::getValue($reqData, 'isTest', 0);

        $data = $this->_myscrmOrganizationService->createOrganization($uniqueName, $friendlyName, $instanceId, $email, $orderCode, $isTest);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 更新测试租户标记
     */
    public function actionUpdateTestOrg()
    {
        $reqData = $this->_request->request();
        $orgCode = ArrayHelper::getValue($reqData, 'orgCode');
        $updateType = ArrayHelper::getValue($reqData, 'updateType', 'add');

        $data = $this->_myscrmOrganizationService->updateTestOrg($orgCode, $updateType);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 根据合同ID应用代码获取项目绑定记录
     */
    public function actionGetProjectBindRecordByContractIdApplicationCode()
    {
        $reqData = $this->_request->request();
        $orgName = ArrayHelper::getValue($reqData, 'orgname', '');
        $contractId = ArrayHelper::getValue($reqData, 'contractId', '');
        $applicationCode = ArrayHelper::getValue($reqData, 'applicationCode', '');
        $pageIndex = ArrayHelper::getValue($reqData, 'pageIndex', 1);
        $pageSize = ArrayHelper::getValue($reqData, 'pageSize', 10);
        $keyword = ArrayHelper::getValue($reqData, 'keyword', '');
        $isQdAdvanced = ArrayHelper::getValue($reqData, 'IsQdAdvanced', 0);

        $data = $this->_authorizeService->getProjectBindRecordByContractIdApplicationCode($orgName, $contractId, $applicationCode, $keyword, $pageIndex, $pageSize, $isQdAdvanced);
        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 项目授权概况列表
     */
    public function actionGetOrgProjectAuthList()
    {
        $reqData = $this->_request->request();
        $areaId = ArrayHelper::getValue($reqData, 'areaId', '');
        $disable = ArrayHelper::getValue($reqData, 'disable', '');
        $orgState = ArrayHelper::getValue($reqData, 'orgState', '');
        $keyword = ArrayHelper::getValue($reqData, 'keyword', '');
        $pageIndex = ArrayHelper::getValue($reqData, 'pageIndex', 1);
        $pageSize = ArrayHelper::getValue($reqData, 'pageSize', 10);

        $data = $this->_myscrmOrganizationService->getOrgProjectAuthList($areaId, $disable, $orgState, $keyword, true, $pageIndex, $pageSize);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 导出项目授权概况
     */
    public function actionExportOrgProjectAuthList()
    {
        $reqData = $this->_request->request();
        $areaId = ArrayHelper::getValue($reqData, 'areaId', '');
        $disable = ArrayHelper::getValue($reqData, 'disable', '');
        $orgState = ArrayHelper::getValue($reqData, 'orgState', '');
        $keyword = ArrayHelper::getValue($reqData, 'keyword', '');

        $data = $this->_myscrmOrganizationService->exportOrgProjectAuthList($areaId, $disable, $orgState, $keyword);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 获取交付信息变更记录
     */
    public function actionGetDeliveryChangeLog()
    {
        $reqData = $this->_request->request();
        $organizationId = ArrayHelper::getValue($reqData, 'organizationId', '');

        $data = $this->_myscrmOrganizationService->getDeliveryChangeLog($organizationId);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 设置合同过期邮件提醒
     */
    public function actionAddRemind()
    {
        $reqData = $this->_request->request();
        $organizationId = ArrayHelper::getValue($reqData, 'organizationId', '');
        $contractId = ArrayHelper::getValue($reqData, 'contractId', '');//当是项目维度时，合同ID为空
        $isStop = ArrayHelper::getValue($reqData, 'isStop', 1);
        $reason = ArrayHelper::getValue($reqData, 'reason', '');
        $isXq = ArrayHelper::getValue($reqData, 'isXq', 1);
        $renewStatus = ArrayHelper::getValue($reqData, 'renewStatus', 0);
        $noRenewReason = ArrayHelper::getValue($reqData, 'noRenewReason', 0);
        $details = ArrayHelper::getValue($reqData, 'details', []);
        $details = json_decode($details);

        $data = $this->_myscrmOrganizationService->addRemind($organizationId, $contractId, $isStop, $reason, $isXq, $details, $renewStatus, $noRenewReason);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 更新合同过期邮件提醒
     */
    public function actionUpdateRemind()
    {
        $reqData = $this->_request->request();
        $organizationId = ArrayHelper::getValue($reqData, 'organizationId', '');
        $remindId = ArrayHelper::getValue($reqData, 'remindId', '');
        $isStop = ArrayHelper::getValue($reqData, 'isStop', 1);
        $reason = ArrayHelper::getValue($reqData, 'reason', '');
        $isXq = ArrayHelper::getValue($reqData, 'isXq', 1);
        $renewStatus = ArrayHelper::getValue($reqData, 'renewStatus', 0);
        $noRenewReason = ArrayHelper::getValue($reqData, 'noRenewReason', 0);
        $details = ArrayHelper::getValue($reqData, 'details', []);
        $details = json_decode($details);

        $data = $this->_myscrmOrganizationService->updateRemind($organizationId, $remindId, $isStop, $reason, $isXq, $renewStatus, $noRenewReason, $details);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 获取合同过期邮件提醒
     */
    public function actionGetRemind()
    {
        $reqData = $this->_request->request();
        //$contractId = ArrayHelper::getValue($reqData, 'contractId', '');
        $organizationId = ArrayHelper::getValue($reqData, 'organizationId', '');
        $projectId = ArrayHelper::getValue($reqData, 'projectId', '');
        $appCode = ArrayHelper::getValue($reqData, 'appCode', '');

        $data = $this->_myscrmOrganizationService->getRemind($organizationId, $projectId, $appCode);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 续签提醒第一步的列表
     */
    public function actionGetRemindDetailsStepOne()
    {
        $reqData = $this->_request->request();
        $contractId = ArrayHelper::getValue($reqData, 'contractId', '');
        $organizationId = ArrayHelper::getValue($reqData, 'organizationId', '');
        $projectName = ArrayHelper::getValue($reqData, 'projectName', '');
        $projectId = ArrayHelper::getValue($reqData, 'projectId', '');

        $data = $this->_authorizeService->getRemindDetailsStepOne($organizationId, $projectName, $contractId, $projectId);
        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 获取合同过期邮件提醒详细表(续签提醒第二步)
     */
    public function actionGetRemindDetails()
    {
        $contractId = Yii::$app->request->get('contractId', '');
        $organizationId = Yii::$app->request->get('organizationId', '');
        $projectIdAndAppCode = Yii::$app->request->post('projectIdAndAppCode', '');
        $projectIdAndAppCode = json_decode($projectIdAndAppCode, true);

        $data = $this->_myscrmOrganizationService->getRemindDetails($organizationId, $contractId, $projectIdAndAppCode);
        return $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /**
     * 获取需要做续签汇报的合同列表
     * 取数规则修改：取所有的合同
     */
    public function actionGetNeedRenewContractList()
    {
        $orgCode = Yii::$app->request->get('orgname', '');

        $data = $this->_authorizeService->getNeedRenewContractList($orgCode);
        return $this->exportJson($data, $this->_authorizeService->getErrCode(), $this->_authorizeService->getErrMsg());
    }

    /**
     * 更新合同交付信息
     * @return mixed
     */
    public function actionUpdateContractDeliverInfo()
    {
        $this->exitIfNotPost();

        $requestData = $this->_request->request();
        if (!array_key_exists('contract_id', $requestData)) {
            $this->json(["retCode" => -1, "result" => false, "retMsg" => "合同ID不能为空"]);
        }

        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try {
            $this->_contractService->updateContractDeliverInfo($requestData);
        } catch (\Exception $ex) {
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            $this->json($response);
        }
        $this->json($response);
    }

    /**
     * 获取交付信息变更记录
     */
    public function actionGetContractDeliveryChangeLog()
    {
        $reqData = $this->_request->request();
        $contractId = ArrayHelper::getValue($reqData, 'contract_id', '');

        $data = $this->_contractService->getContractDeliveryChangeLog($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 租户、合同、项目数量概览
     */
    public function actionContractOverview()
    {
        $data = $this->_contractService->getContractOverview();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 手动同步项目信息接口
     * @throws \Exception
     */
    public function actionSyncOrgProjectAuthList(){
        $this->_authorizeService->syncContractApplicationProject();
        $this->exportJson([],0,"");
    }

    /*
     *
     * Author yuyj
     * Date 2017-01-09
     * @apiVersion 1.0.0
     * @api {post} /api/index.php/mtp/myscrm-organization/set-bq 设置租户百强
     * @apiGroup myscrm-organization-controller
     *
     * @apiParam formData {string} orgId 租户ID
     *
     * @apiResponse 200 {
     *  "retCode": 0,
     *  "errMsg": "",
     *  "data": true
     * }
     */
    public function actionSetBq()
    {
        $orgId = Yii::$app->request->post('orgId', '');
        $data = $this->_myscrmOrganizationService->setBq($orgId);
        $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }

    /*
     *
     * Author yuyj
     * Date 2017-01-09
     * @apiVersion 1.0.0
     * @api {post} /api/index.php/mtp/myscrm-organization/unset-bq 取消租户百强设置
     * @apiGroup myscrm-organization-controller
     *
     * @apiParam formData {string} orgId 租户ID
     *
     * @apiResponse 200 {
     *  "retCode": 0,
     *  "errMsg": "",
     *  "data": true
     * }
     */
    public function actionUnsetBq()
    {
        $orgId = Yii::$app->request->post('orgId', '');
        $data = $this->_myscrmOrganizationService->unsetBq($orgId);
        $this->exportJson($data, $this->_myscrmOrganizationService->getErrCode(), $this->_myscrmOrganizationService->getErrMsg());
    }
}
